package com.pro.framework.json.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.pro.framework.api.enums.IEnumInt;
import com.pro.framework.json.EnumDeserializer;
import com.pro.framework.json.annotation.NoTrim;

import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Set;

public class ObjectMapperBuilder {


    public static ObjectMapper buildObjectMapper() {
        return buildObjectMapper(null);
    }
    public static ObjectMapper buildObjectMapper(Set<Class<IEnumInt>> enumClasses) {
        ObjectMapper objectMapper = new ObjectMapper();
        applyBaseConfiguration(objectMapper, enumClasses);
        return objectMapper;
    }

    public static void applyBaseConfiguration(ObjectMapper objectMapper, Set<Class<IEnumInt>> enumClasses) {
        // 你原有的基础配置
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        // Long转String（解决JS精度问题）
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);

        // 标准时间格式
        simpleModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        simpleModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        simpleModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        simpleModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        simpleModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        simpleModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));

        // 枚举处理
        if (enumClasses != null) {
            //noinspection rawtypes,unchecked
            enumClasses.forEach(enumClass -> simpleModule.addDeserializer(enumClass, new EnumDeserializer<>((Class)enumClass)));
        }

        // 字符串trim处理
        simpleModule.addDeserializer(String.class, new StdDeserializer<String>(String.class) {
            @Override
            public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
                String value = p.getValueAsString();
                if (value == null) return null;

                Object currentBean = p.getCurrentValue();
                if (currentBean != null) {
                    String fieldName = p.currentName();
                    try {
                        Field field = currentBean.getClass().getDeclaredField(fieldName);
                        if (field.isAnnotationPresent(NoTrim.class)) {
                            return value;
                        }
                    } catch (NoSuchFieldException ignored) {}
                }
                return value.trim();
            }
        });

        objectMapper.registerModule(simpleModule);
    }
}
